//
//  XGSeePictureViewController.m
//  BSBuDeJie
//
//  Created by monkey on 2019/1/1.
//  Copyright © 2019 itcast. All rights reserved.
//

#import <Masonry/Masonry.h>
#import <SVProgressHUD/SVProgressHUD.h>
#import <SDWebImage/SDWebImageManager.h>
#import <FLAnimatedImage/FLAnimatedImage.h>
#import <FLAnimatedImage/FLAnimatedImageView.h>

#import "XGSeePictureViewController.h"

#import "UIImageView+Extension.h"
#import "PHPhotoLibrary+Extension.h"

#import "XGTopicModel.h"

#import "XGProgressView.h"

@interface XGSeePictureViewController ()

/// 数据模型
@property (nonatomic,strong) XGTopicModel *topicModel;

/// 滚动视图
@property (nonatomic,strong) UIScrollView *scrollView;
/// 图片视图
@property (nonatomic,strong) FLAnimatedImageView *imageView;
/// 保存按钮
@property (nonatomic,strong) UIButton *saveButton;
/// 下载进度视图
@property (nonatomic,strong) XGProgressView *progressView;

@end

@implementation XGSeePictureViewController

#pragma mark - 控制器生命周期方法

- (void)loadView
{
    [super loadView];
    // 设置视图层次结构
    [self setUpUI];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // 添加手势
    [self.scrollView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeAction)]];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    // 下载图片
    [self downloadImageWithCompletion:^(NSError * _Nullable error, NSData * _Nullable data) {
        if (error) {
            DEBUG_Log(@"大图下载失败\n");
            return;
        }
        
        [self setUpImage:data];
    }];
}

// 隐藏状态栏
- (BOOL)prefersStatusBarHidden
{
    return YES;
}

#pragma mark - 构造函数

- (instancetype)initWithTopicModel:(XGTopicModel *)topicModel
{
    if (self = [super initWithNibName:nil bundle:nil]) {
        self.topicModel = topicModel;
    }
    
    return self;
}

+ (instancetype)viewControllerWithTopicModel:(XGTopicModel *)topicModel
{
    return [[self alloc] initWithTopicModel:topicModel];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    NSException *exp = [NSException exceptionWithName:@"对象创建失败" reason:@"请使用 -initWithTopicModel:或 +viewControllerWithTopicModel:方法创建对象" userInfo:nil];
    [exp raise];
    return self;
}

#pragma mark - 事件监听

- (void)closeAction
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)saveImageAction
{
    NSDictionary *dictionary = [NSBundle mainBundle].infoDictionary;
    NSString *appName = dictionary[@"CFBundleDisplayName"];
    if (self.topicModel.isGif) {
        NSString *filePath = [[SDImageCache sharedImageCache] defaultCachePathForKey:self.topicModel.imageURL];
        [PHPhotoLibrary saveImageWithFileURL:[NSURL fileURLWithPath:filePath] assetCollectionName:appName completionHandle:^(BOOL success, NSError *error) {
            if (error) {
                [SVProgressHUD showErrorWithStatus:@"保存失败"];
                return;
            }
            
            [SVProgressHUD showSuccessWithStatus:@"保存成功"];
        }];
    }
    else {
        [PHPhotoLibrary saveImage:self.imageView.image assetCollectionName:appName completionHandle:^(BOOL success, NSError * _Nullable error) {
            if (error) {
                [SVProgressHUD showErrorWithStatus:@"保存失败"];
                return;
            }
            
            [SVProgressHUD showSuccessWithStatus:@"保存成功"];
        }];
    }
}


#pragma mark - 内部其他私有方法

- (void)setUpUI
{
    // 添加子控件
    [self.view addSubview:self.scrollView];
    [self.view addSubview:self.saveButton];
    [self.view addSubview:self.progressView];
    
    // 设置自动布局
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    [self.saveButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view).offset(-30);
        make.bottom.equalTo(self.view).offset(-30);
    }];
    
    [self.progressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.view);
        make.size.mas_equalTo(CGSizeMake(150, 150));
    }];
}

/** 下载图片 */
- (void)downloadImageWithCompletion:(void (^)(NSError *_Nullable error,NSData *_Nullable data))completion
{
    NSData *data = [[SDWebImageManager sharedManager].imageCache diskImageDataForKey:self.topicModel.imageURL];
    if (data != nil) {
        // 本地有缓存
        completion(nil,data);
    } else {
        // 本地没有缓存 进行网络下载
        self.progressView.hidden = NO;
        [[SDWebImageManager sharedManager] loadImageWithURL:[NSURL URLWithString:self.topicModel.imageURL] options:SDWebImageRefreshCached | SDWebImageRetryFailed progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
            dispatch_async(dispatch_get_main_queue(), ^{
                self.progressView.progress = receivedSize * 1.f / expectedSize;
            });
//            NSLog(@"%.2f",receivedSize * 1.f / expectedSize);
        } completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
            self.progressView.hidden = YES;
            completion(error,data);
        }];
    }
}

/** 设置图片 */
- (void)setUpImage:(NSData *)data
{
    // 刷新自动布局
    [self.view layoutIfNeeded];
    
    // 设置大小
    CGFloat width = self.scrollView.width;
    CGFloat height = width / self.topicModel.width * self.topicModel.height;
    if (height <= self.scrollView.height) {
        self.imageView.size = CGSizeMake(width, height);
        self.imageView.center = self.scrollView.center;
    } else {
        self.imageView.frame = CGRectMake(0, 0, width, height);
        self.scrollView.contentSize = CGSizeMake(0, height);
    }
    
    // 设置图片
    if (!self.topicModel.isGif) {
        self.imageView.image = [UIImage imageWithData:data];
    } else {
        self.imageView.animatedImage = [FLAnimatedImage animatedImageWithGIFData:data];
    }
}

#pragma mark - 懒加载

- (UIScrollView *)scrollView
{
    if (_scrollView == nil) {
        _scrollView = [[UIScrollView alloc] init];
        _scrollView.backgroundColor = [UIColor blackColor];
        _scrollView.bounces = NO;
        _scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        [_scrollView addSubview:self.imageView];
    }
    
    return _scrollView;
}

- (FLAnimatedImageView *)imageView
{
    if (_imageView == nil) {
        _imageView = [[FLAnimatedImageView alloc] init];
    }
    
    return _imageView;
}

- (UIButton *)saveButton
{
    if (_saveButton == nil) {
        _saveButton = [UIButton buttonWithTitle:@"  保存  " fontSize:15 titleColor:[UIColor whiteColor] target:self action:@selector(saveImageAction)];
        _saveButton.backgroundColor = [UIColor darkGrayColor];
    }
    
    return _saveButton;
}

- (XGProgressView *)progressView
{
    if (_progressView == nil) {
        _progressView = [[XGProgressView alloc] init];
        _progressView.backgroundColor = [UIColor clearColor];
        _progressView.userInteractionEnabled = NO;
        _progressView.hidden = YES;
    }
    
    return _progressView;
}


@end
